﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace InitScreenshare
{
  class Program
  {
    static void Main(string[] args)
    {

      if (args[0] == "init")
      {
        bool result = WhriteChromeRegistry();
        int i = 0;
        while (!result && i < 3)
        {
          result = WhriteChromeRegistry();
          i++;
        }        
        SetSysEnvironment();
      }
      else if (args[0] == "uninstall")
      {
        RemoveChromeRegistry();
      }
      
      Console.WriteLine("Done");
    }

    private static void SetSysEnvironment()
    {
      //string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
      //SysEnvironment.SetPathAfter(Path.Combine(appDataPath, "Screenshare", "ChromeNativeHost"));
    }
    private static void RemoveChromeRegistry()
    {
      try
      {
        RegistryHelper.DeleteRegistrySubKey(Registry.CurrentUser, "Software\\Google\\Chrome\\NativeMessagingHosts\\com.mosai.screenshare");
      }
      catch(Exception e)
      {

      }
    }
    private static bool WhriteChromeRegistry()
    {
      try
      {
        bool isExistKey = RegistryHelper.IsRegistryKeyExist(Registry.CurrentUser, "Software\\Google\\Chrome");
        if (!isExistKey)
        {
          Console.WriteLine("注册表写入错误，Chrome浏览器没有安装！");
          return false;
        }

        bool isExistNativeMsgHost = RegistryHelper.IsRegistryKeyExist(Registry.CurrentUser, "Software\\Google\\Chrome\\NativeMessagingHosts");
        if (!isExistNativeMsgHost)
        {
          RegistryHelper.CreateSubKey(Registry.CurrentUser, "Software\\Google\\Chrome\\NativeMessagingHosts");
        }

        bool isExistScreenshare = RegistryHelper.IsRegistryKeyExist(Registry.CurrentUser, "Software\\Google\\Chrome\\NativeMessagingHosts\\com.mosai.screenshare");
        if (!isExistScreenshare)
        {
          RegistryHelper.CreateSubKey(Registry.CurrentUser, "Software\\Google\\Chrome\\NativeMessagingHosts\\com.mosai.screenshare");
        }

        //定义安装目录

        string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
        //string value = Path.Combine("C:\\Screenshare", "ChromeNativeHost", "manifest.json");
        string value = Path.Combine(appDataPath, "Screenshare", "ChromeNativeHost", "manifest.json");
        RegistryHelper.SetRegistryData(Registry.CurrentUser, "Software\\Google\\Chrome\\NativeMessagingHosts\\com.mosai.screenshare", "", value);

        return true;

      }
      catch (Exception e)
      {
        Console.WriteLine(e.Message);
        return false;
      }

    }
  }
}
